package com.example.interviewrecorder.view

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.view.KeyEvent
import android.view.MenuItem
import android.view.View
import androidx.core.view.GravityCompat
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.GridLayoutManager
import com.example.interviewrecorder.LyyApplicaiton
import com.example.interviewrecorder.LyyBaseActivity
import com.example.interviewrecorder.LyyDatabase
import com.example.interviewrecorder.R
import com.example.interviewrecorder.adapter.RecordAdapter
import com.example.interviewrecorder.components.showInfo
import com.example.interviewrecorder.dao.RecordDao
import com.example.interviewrecorder.databinding.ActivityRecordListBinding
import com.example.interviewrecorder.databinding.NavHeaderBinding
import com.example.interviewrecorder.model.Record
import com.example.interviewrecorder.utils.LyyActivityCollector
import com.example.interviewrecorder.utils.LyyLogUtil
import com.example.interviewrecorder.utils.showToast
import com.google.android.material.navigation.NavigationView
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.Timer
import java.util.TimerTask

class RecordListActivity : LyyBaseActivity(), View.OnClickListener,
    NavigationView.OnNavigationItemSelectedListener {
    private val binding: ActivityRecordListBinding by lazy {
        ActivityRecordListBinding.inflate(layoutInflater)
    }
    private val navHeaderBinding: NavHeaderBinding by lazy {
        val headerView = binding.navView.getHeaderView(0)
        NavHeaderBinding.bind(headerView)
    }
    private lateinit var recordList: List<Record>
    private var isExist = false
    private lateinit var timer: Timer
    private val recordDao: RecordDao = LyyDatabase.getDatabase().getRecordDao()
    private val handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when (msg.what) {
                QUERY_ALL_RECORD -> {
                    val adapter = RecordAdapter(recordList)
                    binding.rv.adapter = adapter
                }
            }
        }
    }

    companion object {
        private const val TAG = "RecordListActivity"
        const val QUERY_ALL_RECORD = 1
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        initEvents()
    }

    override fun onResume() {
        super.onResume()
        initData()
    }

    private fun initData() {
        lifecycleScope.launch {
            launch(Dispatchers.IO) {
                var userId = LyyApplicaiton.currUser?.id ?: -1
                val list = recordDao.queryAllRecord(userId)
                recordList = list
                val msg = Message.obtain()
                msg.what = QUERY_ALL_RECORD
                handler.sendMessage(msg)
            }
        }
        val gridLayoutManager = GridLayoutManager(this, 2)
        binding.rv.layoutManager = gridLayoutManager
        LyyLogUtil.d(
            TAG,
            "trueName=${LyyApplicaiton.currUser?.trueName},email=${LyyApplicaiton.currUser?.email}"
        )
        navHeaderBinding.userText.text = LyyApplicaiton.currUser?.trueName.orEmpty()
        navHeaderBinding.mailText.text = LyyApplicaiton.currUser?.email.orEmpty()
    }

    private fun initEvents() {
        binding.faBtn.setOnClickListener(this)
        binding.ivMore.setOnClickListener(this)
        binding.navView.setNavigationItemSelectedListener(this)
        binding.searchEt.addTextChangedListener(afterTextChanged = { editable ->
            lifecycleScope.launch {
                launch(Dispatchers.IO) {
                    repeatOnLifecycle(Lifecycle.State.STARTED) {
                        val searContent = editable.toString()
                        var userId = LyyApplicaiton.currUser?.id ?: -1
                        var list = recordDao.queryRecordByKeywordAndUserId(searContent, userId)
                        recordList = list
                        val msg = Message.obtain()
                        msg.what = QUERY_ALL_RECORD
                        handler.sendMessage(msg)
                    }
                }
            }
        })
    }


    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.faBtn -> startActivity(Intent(this, AddRecordActivity::class.java))
            R.id.iv_more -> {
                binding.drawerLayout.openDrawer(GravityCompat.START)
                clearMenuItemCheckState()
            }
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exist()
        }
        return false
    }

    private fun exist() {
        if (!isExist) {
            isExist = true
            showToast(getString(R.string.exit_again_tip))
            timer = Timer()
            timer.schedule(object : TimerTask() {
                override fun run() {
                    isExist = false
                }
            }, 2000)
        } else {
            LyyActivityCollector.finishAll()
        }
    }

    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.personalData -> {
                PersonalDataActivity.start()
                binding.drawerLayout.closeDrawers()
            }

            R.id.securityCenter -> {
                SecurityCenterActivity.start()
                binding.drawerLayout.closeDrawers()
            }

            R.id.setting -> {
                binding.drawerLayout.closeDrawers()
                SettingActivity.start()
            }

            R.id.about -> {
                binding.drawerLayout.closeDrawers()
                AboutActivity.start()
            }

            R.id.feedback -> {
                binding.drawerLayout.closeDrawers()
                FeedbackActivity.start()
            }

            R.id.exit -> {
                showInfo(
                    title = getString(R.string.tip_title),
                    content = getString(R.string.confirm_exit_app),
                    onPositiveBtnClick = {
                        //点击确定退出应用程序
                        LyyActivityCollector.finishAll()
                    })
            }
        }
        return true
    }

    private fun clearMenuItemCheckState() {
        val menu = binding.navView.menu
        for (i in 0 until menu.size()) {
            menu.getItem(i).isChecked = false
        }
    }
}